package com.qf.kdxf.controller;

import com.qf.kdxf.entity.speechsynthesis.SpeechEntity;
import com.qf.kdxf.service.impl.SpeechSynthesisServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ResourceLoader;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.FileOutputStream;
import java.nio.file.Paths;

@RestController
@RequestMapping("/test")
public class SpeechSynthesisController {
    @Autowired
    SpeechSynthesisServiceImpl speechSynthesisService;
    @Autowired
    ResourceLoader resourceLoader;

    @RequestMapping("/speech")
    public String speech(@RequestBody SpeechEntity speechEntity, HttpServletRequest request){
        String fileName = "speech_"+ System.currentTimeMillis()+".mp3";
        try{
            // 与服务器建立websocket连接的url
            String wsURL = speechSynthesisService.getAuthUrl().replace("https://", "wss://");
            // 获取resource目录下的TestAudio文件夹路径
            String projectRootPath = Paths.get("").toAbsolutePath().toString();
            // 拼接目标文件夹路径
//            String targetFolderPath = projectRootPath + "/src/main/resources/static/TestAudio";
//            File targetFolder = new File(targetFolderPath);
//            if (!targetFolder.exists()) {
//                targetFolder.mkdirs();
//            }
//            // 拼接目标文件路径
//            String loadAddress = targetFolderPath + "/" + fileName;
//            System.out.println("文件下载地址：" + loadAddress);
            String loadAddress = request.getServletContext().getRealPath("/") + fileName;
            FileOutputStream outputStream = new FileOutputStream(loadAddress);
            // 将输出流设置到实体对象中
            speechEntity.setOutput_file_path(outputStream);
            speechEntity.setWsUrl(wsURL);
            // 开始工作
            speechSynthesisService.websocketWork(speechEntity);
            String testUrl="http://localhost:8080/"+ fileName;
            System.out.println(testUrl);
//            return new ResultData(200,"success",fileName);
        }catch (Exception e){
            e.printStackTrace();
//            return new ResultData(500,"error",null);
        }
        return "http://localhost:8080/"+fileName;
    }
}
